//
//  UserAccount.swift
//  Weibo
//
//  Created by 张婷 on 15/10/21.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

/// 用户账户模型
class UserAccount: NSObject, NSCoding {
    
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 需要查询的用户ID
    var uid: String?
    
    /// 过期日期
    var expiresDate: NSDate?
    
    /// 用户昵称
    var screen_name: String?
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    // 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // 调试模型信息
    override var description: String {
        let keys = ["access_token", "expires_in", "uid", "expiresDate", "screen_name", "avatar_large"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    ///  MARK: 归档 & 接档
    ///  归档 - 在将当前对象保存到磁盘前，先对象编码成二进制数据  - 跟序列化很像
    ///
    ///  - parameter aCoder: 编码器
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    }
    
    ///  解档 - 从磁盘加载二进制数据，与网络的反序列化很像
    ///
    ///  - parameter aDecoder: 解码器
    ///
    ///  - returns: 用户账户对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
    }
}
